<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use Hyn\Tenancy\Environment;
use Hyn\Tenancy\Models\Hostname;
use Hyn\Tenancy\Models\Website;
use Hyn\Tenancy\Repositories\HostnameRepository;
use Hyn\Tenancy\Repositories\WebsiteRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class TenantController extends Controller
{
    public function create()
    {
        $companyId = request()->get("companyId");
        if (WebSite::where('uuid', $companyId)->count() > 0) {
            $result = [
                "error" => true,
                "message" => "企业ID已经存在"
            ];
            return response()->json(compact(['result']));
        }
        $website = new Website;
        $website->uuid = $companyId;
        app(WebsiteRepository::class)->create($website);

        $hostname = new Hostname;
        $appUrl = config('app.url');
        $baseUrl = mb_ereg_replace('http:\/\/|https:\/\/', '', $appUrl);
        $hostname->fqdn = $companyId . "." . $baseUrl;
        $hostname = app(HostnameRepository::class)->create($hostname);
        app(HostnameRepository::class)->attach($hostname, $website);
//        $out = Artisan::call("tenancy:migrate:refresh --website_id=$website->id");
        Artisan::call("tenancy:db:seed --force --website_id=$website->id");
        app(Environment::class)->tenant($website);
        Artisan::call('passport:install');
        $result = 'ok';
        return response()->json(compact(['result']));
    }
}
